package main

import (
	"gin/webook/internal/repository"
	"gin/webook/internal/repository/dao"
	"gin/webook/internal/service"
	"gin/webook/internal/web"
	"gin/webook/internal/web/middleware"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

func main() {

	db := InitDb()
	server := InitWebServer()
	InitUserHandler(server, db)
}

func InitDb() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:h13846022944@tcp(localhost:3306)/webook"))
	err = dao.InitTables(db)
	if err != nil {
		panic(err)
	}

	return db
}

func InitWebServer() *gin.Engine {
	server := gin.Default()

	server.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"https://localhost:3000"},
		AllowHeaders:     []string{"Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowOriginFunc: func(origin string) bool {
			return strings.Contains(origin, "localhost")
		},
		MaxAge: 12 * time.Hour,
	}), func(ctx *gin.Context) {

	})

	login := &middleware.LoginMiddlewareBuilder{}
	//存储数据的,也就是你userId存哪里
	store := cookie.NewStore([]byte("secret"))
	//初始化session
	server.Use(sessions.Sessions("ssid", store), login.CheckLogin())

	return server
}

func InitUserHandler(server *gin.Engine, db *gorm.DB) {
	userDao := dao.NewUserDao(db)
	userRepo := repository.NewUserRepository(userDao)
	userService := service.NewUserService(userRepo)
	userHandler := web.NewUserHandler(userService)
	userHandler.RegisterRoutes(server)
	err := server.Run(":8080")
	if err != nil {
		panic(err)
	}
}
